<?php

namespace App\Dao;

use App\Model\FollowList;
use App\Model\User;
use App\Model\VisitList;
use App\Model\VisitListCount;
use App\Utils\FunUtil;
use App\Utils\LoggerUtil;
use App\Utils\MemcacheClient;
use Hyperf\Context\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use function Hyperf\Translation\trans;

class FollowActionDao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }


    /**
     * Note - 有访客，切不是自己访问自己
     * DateTime 2024/7/16 11:03
     * User Admin
     * @param $uid
     * @param $userId
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function addVisit($uid, $userId)
    {
        //24小时内只记录一次到访,如果期间缓存丢失，只是更新到访时间，并不增加一条记录
        if ($uid == $userId) {
            return;
        }

        $this->visit($uid, $userId);
        // 增加记录 清除一二页缓存
        MemcacheClient::getInstance()->delete("my_check_user_" . $uid . "_1");
        MemcacheClient::getInstance()->delete("my_check_user_" . $uid . "_2");
        MemcacheClient::getInstance()->delete("my_visitors_" . $userId . "_1");
        MemcacheClient::getInstance()->delete("my_visitors_" . $userId . "_2");

    }


    /**
     * Note - 增加访客记录，和访客次数
     * DateTime 2024/7/16 11:02
     * User Admin
     * @param $uid
     * @param $userId
     */
    private function visit($uid, $userId)
    {
        $res = VisitList::query()->where('main_id', $uid)->where('guest_id', $userId)->first();
        if (!empty($res)) {
            // VisitList::query()->where('main_id', $uid)->where('guest_id', $userId)->update(['time' => time(), 'is_read' => 0]);
            $res->time = time();
            $res->is_read = 0;
            $res->save();
        } else {
            VisitList::query()->insert([
                'main_id' => $uid,
                'guest_id' => $userId,
                'is_read' => 0,
                'time' => time()
            ]);
        }

        //添加当天的相同用户访问次数
        $need_time = time();
        $curr_date = date('Y-m-d', $need_time);
        $vc_res = VisitListCount::query()->where('main_id', $uid)->where('guest_id', $userId)->where('dates', $curr_date)
            ->first();
        if (!empty($vc_res)) {
            $vc_res->update_time = $need_time;
            $vc_res->visit_count = $vc_res['visit_count'] + 1;
            $vc_res->save();
            // VisitListCount::query()->where('main_id', $uid)->where('guest_id', $userId)->where('dates', $curr_date) ->update(['visit_count' => $vc_res['visit_count'] + 1, 'update_time' => $need_time]);
        } else {
            VisitListCount::query()->insert([
                'main_id' => $uid,
                'guest_id' => $userId,
                'dates' => $curr_date,
                'visit_count' => 1,
                'is_push' => 0,
                'create_time' => $need_time,
                'update_time' => $need_time
            ]);
        }
    }


    /**
     * Note - 获取粉丝列表
     * DateTime 2024/7/19 12:08
     * User Admin
     * @param $uid
     * @param $cache
     * @return array|mixed
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getIdolsCache($uid, $cache = true)
    {
        $ret = MemcacheClient::getInstance()->get("user_idols_uids_" . $uid);
        if ($ret === false || $cache === false) {
            // $ret = array();
            // FollowList::query()->where('main_id', $uid)->get()->toArray();
            // if(!empty($res)){
            //     foreach($res as $v){
            //         $ret[] = $v['guest_id'];
            //     }
            // }
            $this->getIdolsIds($uid);
            MemcacheClient::getInstance()->set("user_idols_uids_" . $uid, $ret, 300);
        }
        return $ret;
    }


    /**
     * 获取粉丝ID
     * @param $uid
     * @return array
     */
    public function getIdolsIds($uid)
    {
        // $sql = "SELECT f.guest_id FROM `".$this->tb_follow_list."` f inner join `".$this->tb_user."` u ON f.guest_id = u.id WHERE u.isdel = ? AND f.main_id = ? ";
        // $pd = $this->createCommand($sql);
        // $pd->execute(array(0,$uid));
        // $result = $pd->fetchAll(PDO::FETCH_ASSOC);
        // $guestIds = DB::table($this->tb_follow_list . ' as f')
        $guestIds = FollowList::query()->from('tb_follow_list as f')
            ->join('tb_user as u', 'f.guest_id', '=', 'u.id')
            ->where('u.isdel', 0)
            ->where('f.main_id', $uid)
            ->pluck('f.guest_id');
        return $guestIds->toArray();
    }


    /**
     * Note - 最近浏览我的用户
     * DateTime 2024/8/8 16:40
     * User Admin
     * @param $uid
     * @param int $page
     * @param int $pageSize
     * @param int $sex
     * @return array
     */
    public function showMyVisitors($uid, int $page = 1, int $pageSize = 12, int $sex = 2)
    {
        // 浏览记录已读
        VisitList::query()->where('guest_id', $uid)->update(['is_read' => 1]);

        $myVisitors = MemcacheClient::getInstance()->get("my_visitors_" . $uid . "_" . $page);
        if ($myVisitors === false) {
            $myVisitors = followListDao::getInstance()->getVisitorsList($uid, $page, $pageSize);
            // 如果男用户当前页小于6，则补充推荐用户
            if (count($myVisitors['data']) < 6 && $page == 1) {
                if ($sex == 1) {
                    $visitor_uid = [];
                    foreach ($myVisitors['data'] as $v) {
                        $visitor_uid[] = $v['id'];
                    }
                    $is_need = 6 - count($myVisitors['data']);
                    $user_list = (new AnchorDao())->recommendList($visitor_uid, $is_need);
                    $myVisitors['data'] = array_merge($myVisitors['data'], $user_list);
                    // $myVisitors['total'] = count($myVisitors['data']);
                }
            }

            foreach ($myVisitors['data'] as &$v) {
                $v['head_image'] = FunUtil::formatHeadImg($v['head_image']);
            }
            MemcacheClient::getInstance()->set("my_visitors_" . $uid . "_" . $page, $myVisitors, 300);
        }
        return $myVisitors;
    }


    /**
     * Note - 我最近浏览过的用户
     * DateTime 2024/8/8 16:20
     * User Admin
     * @param $uid
     * @param int $page
     * @param int $pagesize
     * @return mixed
     */
    public function showMyCheck($uid, int $page = 1, int $pagesize = 12)
    {
        $myCheckUser = MemcacheClient::getInstance()->get("my_check_user_" . $uid . "_" . $page);
        if ($myCheckUser === false) {
            $myCheckUser = FollowListDao::getInstance()->getMyCheckUser($uid, $page, $pagesize);
            foreach ($myCheckUser['data'] as &$v) {
                $v['head_image'] = FunUtil::formatHeadImg($v['head_image']);
            }
            MemcacheClient::getInstance()->set("my_check_user_" . $uid . "_" . $page, $myCheckUser, 300);
        }
        return $myCheckUser;
    }


    /**
     * Note - 我的粉丝
     * DateTime 2024/8/9 18:48
     * User Admin
     * @param $uid
     * @param $language
     * @param $page
     * @param $pagesize
     * @return array|mixed
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function showMyFans($uid, $page, $pagesize, $language)
    {
        $page = ($page - 1) * $pagesize;
        $myfans = MemcacheClient::getInstance()->get("my_fans_" . $uid . "_" . $page);
        if ($myfans === false) {
            $myfans = FollowListDao::getInstance()->getFansList($uid, $page, $pagesize);
            if (!empty($myfans)) {
                $uids = array();
                foreach ($myfans as $v) {
                    $uids[] = $v['id'];
                }
                $userPhotoNum = PhotoDao::getInstance()->getUserPhotoNum($uids);
                $signArr = trans('slogan', [], $language);
                foreach ($myfans as &$val) {
                    if (empty($val['signature'])) {
                        $val['signature'] = $signArr[array_rand($signArr)];
                    }
                    $val['head_image'] = FunUtil::formatHeadImg($val['head_image']);
                    $val['photo_num'] = $userPhotoNum[$val['id']] ?? 0;
                }
            }
            empty($myfans) && $myfans = array();
            // MemcacheClient::getInstance()->set("my_fans_" . $uid . "_" . $page, $myfans, 300);
        }
        return $myfans;
    }


    /**
     * Note - 我的关注
     * DateTime 2024/8/9 19:08
     * User Admin
     * @param $uid
     * @param $page
     * @param $pagesize
     * @return array
     */
    public function showMyIdols($uid, $page, $pagesize, $language)
    {
        $myidols = MemcacheClient::getInstance()->get("my_idols_" . $uid . "_" . $page);
        if ($myidols === false) {
            $myidols = FollowListDao::getInstance()->getIdolsList($uid, $page, $pagesize);
            if (!empty($myidols)) {
                $uids = array();
                foreach ($myidols as $v) {
                    $uids[] = $v['id'];
                }
                $userPhotoNum = PhotoDao::getInstance()->getUserPhotoNum($uids);
                $signArr = trans('slogan', [], $language);
                foreach ($myidols as &$val) {
                    if (empty($val['signature'])) {
                        $val['signature'] = $signArr[array_rand($signArr)];
                    }
                    $val['head_image'] = FunUtil::formatHeadImg($val['head_image']);
                    $val['photo_num'] = $userPhotoNum[$val['id']] ?? 0;
                }
            }
            empty($myidols) && $myidols = array();
            MemcacheClient::getInstance()->set("my_idols_" . $uid . "_" . $page, $myidols, 300);
        }
        return $myidols;
    }


    /**
     * Note - 相互关注的用户列表
     * DateTime 2024/8/9 19:25
     * User Admin
     * @param $uid
     * @param $page
     * @param $pagesize
     * @param $language
     * @return array|mixed
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function showMutualUser($uid, $page, $pagesize, $language)
    {
        $list = MemcacheClient::getInstance()->get("mutual_user_" . $uid . "_" . $page);
        if ($list === false) {
            $list = FollowListDao::getInstance()->getMutualList($uid, $page, $pagesize);
            if (!empty($list)) {
                $uids = array();
                foreach ($list as $v) {
                    $uids[] = $v['id'];
                }
                $userPhotoNum = PhotoDao::getInstance()->getUserPhotoNum($uids);
                $signArr = trans('slogan', [], $language);
                foreach ($list as &$val) {
                    if (empty($val['signature'])) {
                        $val['signature'] = $signArr[array_rand($signArr)];
                    }
                    $val['head_image'] = FunUtil::formatHeadImg($val['head_image']);
                    $val['photo_num'] = $userPhotoNum[$val['id']] ?? 0;
                }
            }
            empty($list) && $list = array();
            MemcacheClient::getInstance()->set("mutual_user_" . $uid . "_" . $page, $list, 300);
        }
        return $list;
    }


    /**
     * Note - 密友列表
     * DateTime 2024/8/9 19:24
     * User Admin
     * @param $uid
     * @param $page
     * @param $pagesize
     * @param $sex
     * @return array
     */
    public function showCloseness($uid, $page, $pagesize, $sex, $language)
    {
        $closeness = FollowListDao::getInstance()->getClosenessList($uid, $page, $pagesize, $sex);
        if (!empty($closeness)) {
            $uids = array();
            foreach ($closeness as $v) {
                $uids[] = $v['id'];
            }
            $userPhotoNum = PhotoDao::getInstance()->getUserPhotoNum($uids);
            $signArr = trans('slogan', [], $language);
            foreach ($closeness as &$val) {
                // 用户隐藏通话状态
                if ($val['hide_call_status'] && $val['online'] == 2) {
                    $val['online'] = 1;
                }
                if (empty($val['signature'])) {
                    $val['signature'] = $signArr[array_rand($signArr)];
                }
                $val['head_image'] = FunUtil::formatHeadImg($val['head_image']);
                $val['photo_num'] = $userPhotoNum[$val['id']] ?? 0;
                $val['is_new_user'] = $val['register_time'] + 7 * 86400 >= time() ? 1 : 0;// 7天新用户
            }
        }
        empty($closeness) && $closeness = array();
        return $closeness;
    }


}